import React, { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Container,
  Box,
  Typography,
  Button,
  IconButton,
  Grid,
  Card,
  CardContent,
  CardActions,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Tabs,
  Tab,
  Checkbox,
  Alert,
  CircularProgress,
  Paper
} from '@mui/material';
import {
  Restore as RestoreIcon,
  Delete as DeleteIcon,
  ArrowBack as ArrowBackIcon,
  Close as CloseIcon
} from '@mui/icons-material';
import axios from 'axios';
import { debounce } from 'lodash';
import ImagePreviewDialog from '../components/ImagePreviewDialog';

// 使用环境变量中的 API URL
const API_URL = process.env.REACT_APP_API_URL || 'http://localhost:5000';

function Trash() {
  const navigate = useNavigate();
  const [tab, setTab] = useState(0);
  const [albums, setAlbums] = useState([]);
  const [photos, setPhotos] = useState([]);
  const [selectedItems, setSelectedItems] = useState([]);
  const [confirmDialog, setConfirmDialog] = useState(false);
  const [clearDialog, setClearDialog] = useState(false);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);
  const [deleteLoading, setDeleteLoading] = useState(false);
  const [previewPhotoIndex, setPreviewPhotoIndex] = useState(-1);
  const [previewPhotoList, setPreviewPhotoList] = useState([]);
  const [viewAlbum, setViewAlbum] = useState(null); // 当前查看的回收站相册
  const [albumPhotos, setAlbumPhotos] = useState([]); // 当前相册下的照片
  const [albumLoading, setAlbumLoading] = useState(false);
  const [albumSelectedPhotos, setAlbumSelectedPhotos] = useState([]); // 预览窗口中选中的照片
  const [albumDeleteConfirm, setAlbumDeleteConfirm] = useState(false); // 预览窗口删除确认对话框
  const [successMessage, setSuccessMessage] = useState('');

  // 分离相册和照片的获取函数
  const fetchAlbums = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await axios.get(`${API_URL}/api/albums/trash`);
      setAlbums(response.data);
    } catch (error) {
      console.error('获取回收站相册失败:', error);
      setError(error.response?.data?.message || '获取相册失败');
    } finally {
      setLoading(false);
    }
  }, []);

  const fetchPhotos = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await axios.get(`${API_URL}/api/photos/trash`);
      setPhotos(response.data);
    } catch (error) {
      console.error('获取回收站照片失败:', error);
      setError(error.response?.data?.message || '获取照片失败');
    } finally {
      setLoading(false);
    }
  }, []);

  // 根据当前标签页获取数据
  useEffect(() => {
    if (tab === 0) {
      fetchAlbums();
    } else {
      fetchPhotos();
    }
  }, [tab, fetchAlbums, fetchPhotos]);

  // 使用 useCallback 包装防抖函数
  const debouncedFetchAlbums = useCallback(
    debounce(() => {
      fetchAlbums();
    }, 300),
    [fetchAlbums]
  );

  const debouncedFetchPhotos = useCallback(
    debounce(() => {
      fetchPhotos();
    }, 300),
    [fetchPhotos]
  );

  // 使用防抖函数
  useEffect(() => {
    debouncedFetchAlbums();
    return () => {
      debouncedFetchAlbums.cancel();
    };
  }, [debouncedFetchAlbums]);

  useEffect(() => {
    debouncedFetchPhotos();
    return () => {
      debouncedFetchPhotos.cancel();
    };
  }, [debouncedFetchPhotos]);

  const handleRestore = async (item) => {
    try {
      setLoading(true);
      setError(null);
      if (item.type === 'album') {
        await axios.post(`${API_URL}/api/albums/${item._id}/restore`);
        // 直接从相册列表中移除恢复的相册
        setAlbums(prevAlbums => prevAlbums.filter(album => album._id !== item._id));
        // 如果当前正在查看该相册，关闭预览窗口
        if (viewAlbum && viewAlbum._id === item._id) {
          setViewAlbum(null);
        }
      } else {
        await axios.post(`${API_URL}/api/photos/${item._id}/restore`);
        // 直接从照片列表中移除恢复的照片
        setPhotos(prevPhotos => prevPhotos.filter(photo => photo._id !== item._id));
      }
    } catch (error) {
      console.error('恢复失败:', error);
      setError(error.response?.data?.message || '恢复失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  const handleSelectItem = (item) => {
    setSelectedItems(prev => 
      prev.some(i => i._id === item._id)
        ? prev.filter(i => i._id !== item._id)
        : [...prev, item]
    );
  };

  const handleBatchRestore = async () => {
    try {
      setLoading(true);
      setError(null);
      await Promise.all(selectedItems.map(item => 
        axios.post(`${API_URL}/api/${item.type}s/${item._id}/restore`)
      ));
      
      // 直接从列表中移除恢复的选中项目
      if (tab === 0) {
        setAlbums(prevAlbums => prevAlbums.filter(album => 
          !selectedItems.some(selectedItem => selectedItem._id === album._id)
        ));
      } else {
        setPhotos(prevPhotos => prevPhotos.filter(photo => 
          !selectedItems.some(selectedItem => selectedItem._id === photo._id)
        ));
      }

      setSelectedItems([]);

    } catch (error) {
      console.error('批量恢复失败:', error);
      setError(error.response?.data?.message || '批量恢复失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  const handleBatchDelete = async () => {
    try {
      setDeleteLoading(true);
      setError(null);
      const items = Array.isArray(selectedItems) ? selectedItems : [];
      await Promise.all(items.map(item => 
        axios.delete(`${API_URL}/api/${item.type}s/${item._id}/permanent?confirm=true`)
      ));
      setSelectedItems([]);
      setConfirmDialog(false);
      // 根据当前标签页刷新数据
      if (tab === 0) {
        fetchAlbums();
      } else {
        fetchPhotos();
      }
    } catch (error) {
      console.error('批量删除失败:', error);
      setError(error.response?.data?.message || '批量删除失败，请重试');
    } finally {
      setDeleteLoading(false);
    }
  };

  const handleClearTrash = async () => {
    try {
      setDeleteLoading(true);
      setError(null);
      const response = await axios.delete(`${API_URL}/api/photos/clear-trash`);
      
      // 显示清空结果
      const { deletedPhotos, deletedAlbums } = response.data;
      setSuccessMessage(`回收站已清空，共删除 ${deletedPhotos} 张照片和 ${deletedAlbums} 个相册`);
      
      setClearDialog(false);
      // 清空后刷新当前标签页的数据
      if (tab === 0) {
        fetchAlbums();
      } else {
        fetchPhotos();
      }
    } catch (error) {
      console.error('清空回收站失败:', error);
      setError(error.response?.data?.message || '清空回收站失败，请重试');
    } finally {
      setDeleteLoading(false);
    }
  };

  // 查看回收站相册内图片
  const handleViewAlbum = async (album) => {
    setViewAlbum(album);
    setAlbumLoading(true);
    try {
      const response = await axios.get(`${API_URL}/api/photos/trash?albumId=${album._id}`);
      setAlbumPhotos(response.data);
    } catch (error) {
      setAlbumPhotos([]);
    } finally {
      setAlbumLoading(false);
    }
  };

  // 删除回收站相册内的图片（彻底删除）
  const handleDeletePhotoInAlbum = async (photoIds) => {
    try {
      setAlbumLoading(true);
      await Promise.all(photoIds.map(photoId => 
        axios.delete(`${API_URL}/api/photos/${photoId}/permanent?confirm=true`)
      ));
      setAlbumPhotos(prev => prev.filter(p => !photoIds.includes(p._id)));
      setAlbumSelectedPhotos([]);
      setAlbumDeleteConfirm(false);
    } catch (error) {
      setError(error.response?.data?.message || '删除失败，请重试');
    } finally {
      setAlbumLoading(false);
    }
  };

  const handleSelectPhotoInAlbum = (photoId) => {
    setAlbumSelectedPhotos(prev => 
      prev.includes(photoId)
        ? prev.filter(id => id !== photoId)
        : [...prev, photoId]
    );
  };

  const handleSelectAllPhotosInAlbum = () => {
    if (albumSelectedPhotos.length === albumPhotos.length) {
      setAlbumSelectedPhotos([]);
    } else {
      setAlbumSelectedPhotos(albumPhotos.map(p => p._id));
    }
  };

  // 打开图片预览（支持多图）
  const openPreview = (photos, index) => {
    setPreviewPhotoList(photos);
    setPreviewPhotoIndex(index);
  };
  const closePreview = () => {
    setPreviewPhotoIndex(-1);
    setPreviewPhotoList([]);
  };
  const handlePreviewIndexChange = (idx) => setPreviewPhotoIndex(idx);

  return (
    <Container maxWidth="lg" sx={{ mt: 4, mb: 4 }}>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 4, flexDirection: { xs: 'column', sm: 'row' }, gap: 2 }}>
        <Box sx={{ display: 'flex', alignItems: 'center' }}>
          <IconButton onClick={() => navigate('/')} sx={{ mr: 2 }}>
            <ArrowBackIcon />
          </IconButton>
          <Typography variant="h4" component="h1">
            回收站
          </Typography>
        </Box>
        <Box sx={{ display: 'flex', gap: 2, flexDirection: { xs: 'column', sm: 'row' } }}>
          {selectedItems.length > 0 && (
            <>
              <Button
                variant="outlined"
                startIcon={<RestoreIcon />}
                onClick={handleBatchRestore}
                disabled={loading}
                fullWidth
              >
                恢复选中 ({selectedItems.length})
              </Button>
              <Button
                variant="outlined"
                color="error"
                startIcon={<DeleteIcon />}
                onClick={() => setConfirmDialog(true)}
                disabled={loading}
                fullWidth
              >
                永久删除选中
              </Button>
            </>
          )}
          <Button
            variant="contained"
            color="error"
            startIcon={<DeleteIcon />}
            onClick={() => setClearDialog(true)}
            disabled={loading}
            fullWidth
          >
            清空回收站
          </Button>
        </Box>
      </Box>

      <Grid container spacing={3}>
        <Grid item xs={12}>
          <Paper sx={{ p: 2, display: 'flex', flexDirection: 'column' }}>
            <Box sx={{ borderBottom: 1, borderColor: 'divider', mb: 2 }}>
              <Tabs value={tab} onChange={(e, newValue) => setTab(newValue)}>
                <Tab label="相册" />
                <Tab label="照片" />
              </Tabs>
            </Box>

            {error && (
              <Alert severity="error" sx={{ mb: 2 }}>
                {error}
              </Alert>
            )}

            {successMessage && (
              <Alert severity="success" sx={{ mb: 2 }} onClose={() => setSuccessMessage('')}>
                {successMessage}
              </Alert>
            )}

            {loading ? (
              <Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
                <CircularProgress />
              </Box>
            ) : (
              <Grid container spacing={3}>
                {tab === 0
                  ? albums.map((album) => (
                      <Grid item xs={12} sm={6} md={4} key={album._id}>
                        <Card>
                          <CardContent sx={{ cursor: 'pointer' }} onClick={() => handleViewAlbum(album)}>
                            <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
                              <Checkbox
                                checked={selectedItems.some(item => item._id === album._id)}
                                onChange={(e) => {
                                  e.stopPropagation();
                                  handleSelectItem({ ...album, type: 'album' });
                                }}
                                disabled={loading}
                              />
                              <Typography variant="h6" component="h2">
                                {album.name}
                              </Typography>
                            </Box>
                            <Typography color="textSecondary" gutterBottom>
                              {album.description}
                            </Typography>
                            <Typography variant="body2" color="textSecondary">
                              删除时间: {new Date(album.deletedAt).toLocaleString()}
                            </Typography>
                          </CardContent>
                          <CardActions>
                            <IconButton
                              size="small"
                              color="primary"
                              onClick={(e) => {
                                e.stopPropagation();
                                handleRestore({ ...album, type: 'album' });
                              }}
                              disabled={loading}
                            >
                              <RestoreIcon />
                            </IconButton>
                            <IconButton
                              size="small"
                              color="error"
                              onClick={(e) => {
                                e.stopPropagation();
                                setSelectedItems([{ ...album, type: 'album' }]);
                                setConfirmDialog(true);
                              }}
                              disabled={loading}
                            >
                              <DeleteIcon />
                            </IconButton>
                          </CardActions>
                        </Card>
                      </Grid>
                    ))
                  : photos.map((photo, idx) => (
                      <Grid item xs={12} sm={6} md={4} key={photo._id}>
                        <Card>
                          <CardContent>
                            <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
                              <Checkbox
                                checked={selectedItems.some(item => item._id === photo._id)}
                                onChange={() => handleSelectItem({ ...photo, type: 'photo' })}
                                disabled={loading}
                              />
                              <Typography variant="h6" component="h2">
                                {photo.originalName}
                              </Typography>
                            </Box>
                            <Typography variant="body2" color="textSecondary">
                              删除时间: {new Date(photo.deletedAt).toLocaleString()}
                            </Typography>
                            <Box sx={{ mt: 2, textAlign: 'center' }}>
                              <img
                                src={`${API_URL}/uploads/thumbnails/${photo.datePath}/${photo.filename}`}
                                alt={photo.originalName}
                                style={{ maxWidth: '100%', maxHeight: 160, borderRadius: 8, cursor: 'pointer' }}
                                onClick={() => openPreview(photos.map(p => ({
                                  ...p,
                                  src: `${API_URL}/uploads/thumbnails/${p.datePath}/${p.filename}`
                                })), idx)}
                              />
                            </Box>
                          </CardContent>
                          <CardActions>
                            <IconButton
                              size="small"
                              color="primary"
                              onClick={() => handleRestore({ ...photo, type: 'photo' })}
                              disabled={loading}
                            >
                              <RestoreIcon />
                            </IconButton>
                            <IconButton
                              size="small"
                              color="error"
                              onClick={() => {
                                setSelectedItems([{ ...photo, type: 'photo' }]);
                                setConfirmDialog(true);
                              }}
                              disabled={loading}
                            >
                              <DeleteIcon />
                            </IconButton>
                          </CardActions>
                        </Card>
                      </Grid>
                    ))}
              </Grid>
            )}
          </Paper>
        </Grid>
      </Grid>

      <Dialog open={confirmDialog} onClose={() => !deleteLoading && setConfirmDialog(false)}>
        <DialogTitle>确认永久删除</DialogTitle>
        <DialogContent>
          <Typography>
            确定要永久删除选中的{selectedItems.length}个{tab === 0 ? '相册' : '照片'}吗？此操作不可恢复。
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setConfirmDialog(false)} disabled={deleteLoading}>
            取消
          </Button>
          <Button 
            onClick={handleBatchDelete} 
            color="error"
            disabled={deleteLoading}
            startIcon={deleteLoading ? <CircularProgress size={20} /> : null}
          >
            {deleteLoading ? '删除中...' : '永久删除'}
          </Button>
        </DialogActions>
      </Dialog>

      <Dialog open={clearDialog} onClose={() => !deleteLoading && setClearDialog(false)}>
        <DialogTitle>确认清空回收站</DialogTitle>
        <DialogContent>
          <Typography>
            确定要清空回收站吗？此操作将永久删除所有已删除的相册和照片，且不可恢复。
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setClearDialog(false)} disabled={deleteLoading}>
            取消
          </Button>
          <Button 
            onClick={handleClearTrash} 
            color="error"
            disabled={deleteLoading}
            startIcon={deleteLoading ? <CircularProgress size={20} /> : null}
          >
            {deleteLoading ? '清空中...' : '清空回收站'}
          </Button>
        </DialogActions>
      </Dialog>

      {/* 回收站相册内图片查看弹窗 */}
      <Dialog open={!!viewAlbum} onClose={() => {
        setViewAlbum(null);
        setAlbumSelectedPhotos([]);
      }} maxWidth="md" fullWidth>
        <DialogTitle>
          <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <Box sx={{ display: 'flex', alignItems: 'center' }}>
              <Checkbox
                checked={albumSelectedPhotos.length === albumPhotos.length && albumPhotos.length > 0}
                indeterminate={albumSelectedPhotos.length > 0 && albumSelectedPhotos.length < albumPhotos.length}
                onChange={handleSelectAllPhotosInAlbum}
              />
              <Typography variant="h6" component="div">
                {viewAlbum?.name || '相册图片'} (回收站)
              </Typography>
            </Box>
            <Box>
              {albumSelectedPhotos.length > 0 && (
                <Button
                  variant="outlined"
                  color="error"
                  startIcon={<DeleteIcon />}
                  onClick={() => setAlbumDeleteConfirm(true)}
                  sx={{ mr: 2 }}
                >
                  彻底删除选中 ({albumSelectedPhotos.length})
                </Button>
              )}
              <IconButton
                aria-label="close"
                onClick={() => {
                  setViewAlbum(null);
                  setAlbumSelectedPhotos([]);
                }}
                sx={{ color: 'grey.500' }}
              >
                <CloseIcon />
              </IconButton>
            </Box>
          </Box>
        </DialogTitle>
        <DialogContent>
          {albumLoading ? (
            <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: 200 }}>
              <CircularProgress />
            </Box>
          ) : (
            <Grid container spacing={2}>
              {albumPhotos.length === 0 ? (
                <Grid item xs={12} sx={{ textAlign: 'center', color: 'text.secondary', py: 4 }}>
                  暂无图片
                </Grid>
              ) : (
                albumPhotos.map((photo, idx) => (
                  <Grid item xs={12} sm={6} md={4} key={photo._id}>
                    <Box sx={{ position: 'relative', textAlign: 'center' }}>
                      <Checkbox
                        checked={albumSelectedPhotos.includes(photo._id)}
                        onChange={() => handleSelectPhotoInAlbum(photo._id)}
                        sx={{
                          position: 'absolute',
                          top: 8,
                          left: 8,
                          zIndex: 1,
                          bgcolor: 'rgba(255,255,255,0.7)',
                          '&:hover': {
                            bgcolor: 'rgba(255,255,255,0.9)',
                          },
                        }}
                      />
                      <img
                        src={`${API_URL}/uploads/thumbnails/${photo.datePath}/${photo.filename}`}
                        alt={photo.originalName}
                        style={{ maxWidth: '100%', maxHeight: 160, borderRadius: 8, cursor: 'pointer' }}
                        onClick={() => openPreview(albumPhotos.map(p => ({
                          ...p,
                          src: `${API_URL}/uploads/thumbnails/${p.datePath}/${p.filename}`
                        })), idx)}
                      />
                      <IconButton
                        size="small"
                        color="error"
                        sx={{ position: 'absolute', top: 8, right: 8, bgcolor: 'rgba(255,255,255,0.7)' }}
                        onClick={(e) => {
                          e.stopPropagation();
                          setAlbumSelectedPhotos([photo._id]);
                          setAlbumDeleteConfirm(true);
                        }}
                      >
                        <DeleteIcon />
                      </IconButton>
                    </Box>
                  </Grid>
                ))
              )}
            </Grid>
          )}
        </DialogContent>
      </Dialog>

      {/* 预览窗口删除确认对话框 */}
      <Dialog open={albumDeleteConfirm} onClose={() => !albumLoading && setAlbumDeleteConfirm(false)}>
        <DialogTitle>确认彻底删除</DialogTitle>
        <DialogContent>
          <Typography>
            确定要彻底删除选中的{albumSelectedPhotos.length}张照片吗？此操作将永久删除照片，且不可恢复。
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setAlbumDeleteConfirm(false)} disabled={albumLoading}>
            取消
          </Button>
          <Button 
            onClick={() => handleDeletePhotoInAlbum(albumSelectedPhotos)} 
            color="error"
            disabled={albumLoading}
            startIcon={albumLoading ? <CircularProgress size={20} /> : null}
          >
            {albumLoading ? '删除中...' : '彻底删除'}
          </Button>
        </DialogActions>
      </Dialog>

      {/* 图片预览弹窗 */}
      <ImagePreviewDialog
        open={previewPhotoIndex >= 0}
        onClose={closePreview}
        images={previewPhotoList}
        currentIndex={previewPhotoIndex}
        onIndexChange={handlePreviewIndexChange}
      />
    </Container>
  );
}

export default Trash; 